home *** CD-ROM | disk | FTP | other *** search
Text File | 1996-05-21 | 1.6 KB | 73 lines | [TEXT/ttxt] |
- --<<<
- -- Kaleida Labs, Inc.
- -- Field Guide to the ScriptX Language
- -- chapter 5, example 4
-
- -- create a module to avoid naming conflicts
- module Scratch18 uses ScriptX end
- in module Scratch18
-
- -- anonymous functions examples
- -- declare globals
- global cubeMe, reagan, speech, myCounter, anotherCounter
-
- (n -> n * n )
- (a b -> a + b )
- (#rest nums -> for i in nums do print (i * 10))
-
- function addtwo a b -> a + b
- addtwo 4 5
- (a b -> a + b ) 4 5
-
- for i in #(1,2,3,4) collect (n -> n * n) i
-
- cubeMe := (a -> a * a * a)
- cubeMe 2
-
- -- this is OK
- function sumTheNum arg -> (
- if arg <= 0 then return 0
- else return (arg + (sumTheNum (arg - 1)))
- )
- sumTheNum 2
- sumTheNum 10
-
- -- not an efficient way to do recursion
- sumTheNum2 := (arg -> (
- if arg = 0 then return 0
- else return (arg + (sumTheNum2 (arg - 1)))
- ))
-
- -- even an actor can be president
- global reagan := new String string:""
- global speech := "Facts are stupid things"
- for i in speech collect into reagan by \
- (sequence value -> prepend sequence value; sequence) i
-
- -- examples of closures
- function closureMaker -> (
- -- x is the free variable or closure variable
- local x := theCalendarClock.time
- -- elapsedTime is the function that will be returned as a closure
- local fn elapsedTime -> (
- local result := theCalendarClock.time - x
- x := theCalendarClock.time
- result
- )
- -- the next expression is the return value of this function
- -- it returns the local function elapsedTime
- -- that turns it into a closure
- elapsedTime
- )
- timeKeeper := closureMaker()
- timeKeeper()
-
- function counter -> (local x:0; (-> x := x + 1))
- myCounter := counter()
- myCounter()
- myCounter()
- myCounter()
-
- global anotherCounter := counter()
- anotherCounter()
- -->>>